import axios from 'axios'
import { Base64 } from 'js-base64'

export function downloadFormURL(url) {
  let a = document.createElement('a')
  a.href = url
  a.download = url
  a.click()
  a = null
}
export function downloadFormBlob(res, fileNameUsebase64 = true) {
  //导出文件
  // 通过a标签打开新页面下载文件
  let a = document.createElement('a')
  // 构造一个blob对象来处理数据
  let blob = new Blob([res.data])
  if (res.headers['content-disposition']) {
    // 拿到用户上传的文件名
    let fileName = res.headers['content-disposition']
    // 截取=之后的字符串
    fileName = fileName.substring(fileName.indexOf('='))
    fileName = fileName.substring(1).replace(/^\"/, '').replace(/\"$/, '')
    // // 编码转换为中文
    // gbkconvert(fileName, res => {
    //   fileName = res
    //   // URL.createObjectURL()会产生一个url字符串，可以像使用普通 URL 那样使用它，比如用在 img.src 上
    //   a.href = URL.createObjectURL(blob)
    //   // a标签里有download属性可以自定义文件名
    //   a.setAttribute('download', fileName)
    //   document.body.appendChild(a)
    //   a.click()
    //   document.body.removeChild(a)
    // })
    a.href = URL.createObjectURL(blob)
    // a标签里有download属性可以自定义文件名
    a.setAttribute(
      'download',
      fileNameUsebase64 ? Base64.decode(fileName) : fileName,
    )
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
}
export function uploadFile(
  axiosConfig,
  file,
  filename = 'fileData',
  method = 'post',
) {
  const controller = new AbortController()
  // let config = {
  //   signal: controller.signal,
  //   onUploadProgress: progressEvent => {
  //     let percent = Math.round(
  //       (progressEvent.loaded * 100) / progressEvent.total,
  //     )
  //     console.log(`上传进度: ${percent}%`)
  //   },
  // }

  let [url, data, config, ...other] = axiosConfig
  let formData = new FormData()
  formData.append(filename, file)
  Object.keys(data).forEach(key => {
    formData.append(key, data[key])
  })

  let upload = axios[method](
    url,
    formData,
    { ...config, signal: controller.signal },
    ...other,
  )
  console.log(url, formData, { ...config, signal: controller.signal }, ...other)

  return {
    upload,
    cancel: () => controller.abort(), // 暂停/取消上传
  }
}
